#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
from tkinter import StringVar, Button

from base.BaseSubWindow import BaseSubWindow
from sdautolayout.sdautolayout import sdautolayout
from utils.BrowserUtils import BrowserUtils
from widget.ComboboxExt import ComboboxExt


class ChannelWindow(BaseSubWindow):
    def __init__(self, root):
        super(ChannelWindow, self).__init__(root=root, width=400, height=50)
        self.title("推广渠道")
        self.init_ui()
        self.init_data()

    def init_ui(self):
        self.str_channel = StringVar()
        self.cbx_channel = ComboboxExt(self, textvariable=self.str_channel)
        self.cbx_channel.place(x=5, y=5)
        sdautolayout.forWidget(self.cbx_channel).widthIs(100).heightIs(30)
        self.cbx_channel["state"] = "readonly"

        self.str_sub_channel = StringVar()
        self.cbx_sub_channel = ComboboxExt(self, textvariable=self.str_sub_channel)
        self.cbx_sub_channel.place(x=5, y=5)
        sdautolayout.forWidget(self.cbx_sub_channel).widthIs(100).heightIs(30).leftSpaceToView(self.cbx_channel,5)
        self.cbx_sub_channel["state"] = "readonly"


        self.button = Button(self,text='跳转',command=self.toChannel)
        self.button.place(x = 5,y=5)
        sdautolayout.forWidget(self.button).widthIs(100).leftSpaceToView(self.cbx_sub_channel, 5)


    def init_data(self):
        settings = self.getSettings()
        dict_name_sub_channel = {}

        dict_channel = {}
        for channel in settings["channel"]:
            dict_channel[channel["name"]]=channel["login_url"]
            dict_name_sub_channel[channel["name"]] = channel["sub_channel"] #Build (k,v) for (name,sub_channel)

        self.cbx_channel.set_dict(dict_channel)  # 设置下拉列表的值
        self.cbx_channel.current(0)

        dict_sub_channel = {}
        for channel in dict_name_sub_channel[self.cbx_channel.get()]:
            dict_sub_channel[channel["name"]] = channel["url"]

        self.cbx_sub_channel.set_dict(dict_sub_channel)  # 设置子下拉列表的值
        self.cbx_sub_channel.current(0)


    def toChannel(self):
        BrowserUtils.instance().load(self.cbx_sub_channel.value())

    def currentDir(self):
        return os.path.split(os.path.realpath(__file__))[0];

